import Axios from 'axios';
import router from '@/router';
import {Message} from 'element-ui'


// 全局拦截请求，获取到错误
// 请求到结果的拦截处理
Axios.interceptors.response.use( (config: any) => {
    // 返回请求正确的结果
    if (config.data.code === -1) {
        router.push({path: '/login'});  // 进入登陆页面
    }else{
        
    }
    return config.data;
}, (error: any) => {
    if (error&&error.response) {
        switch(error.response.status){
            case 400:
            error.message = '请求错误（404）'
            break
            default:
            error.message = '请求其他错误（未知错误码）'
        }
        
    }else{
        error.message ='连接服务器失败！'
    }

    Message.error(error.message);
    return Promise.reject(error);
    // 错误的请求结果处理，这里的代码根据后台的状态码来决定错误的输出信息
});




const httpServer = (opts: any) => {
    const httpDefaultOpts = { // http默认配置
        method: opts.method,
        baseURL: 'https://xxxx.com',  // 测试
        url: opts.url,
        timeout: 100000,
        params: opts.params,
        data: opts.params,
        headers: opts.method == 'get' ? {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8',
            'systoken': '',
        } : {
                'Content-Type': 'application/json;charset=UTF-8',
                'systoken': '',
            },
    };
    //     if (getToken()) {
    //     const token: any = getToken();
    //     httpDefaultOpts.headers.systoken = token;
    // }
    if (opts.method == 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
    const promise = new Promise(function (resolve, reject) {
        Axios(httpDefaultOpts).then(
            (res) => {
                if (res.data.code == -3) {
                    resolve(res.data);
                } else {
                    resolve(res.data);
                }
            },
        ).catch(
            (response) => {
                reject(response);
            },
        );
    });
    return promise;
};


export default httpServer;

